import Vue from "vue";
import axios from "axios";
import store from "@/store";
import { VueAxios } from "./axios";

import { ACCESS_TOKEN } from "@/store/mutation-types";
import signMd5Utils from "@/utils/encryption/signMd5Utils";
import router from "@/router";

/**
 * 【指定 axios的 baseURL】
 * 如果手工指定 baseURL: '/jeecg-boot'
 * 则映射后端域名，通过 vue.config.js
 * @type {*|string}
 */
let apiBaseUrl = window._CONFIG["domianURL"] || "/api";
//console.log("apiBaseUrl= ",apiBaseUrl)
// 创建 axios 实例
const service = axios.create({
  baseURL: apiBaseUrl, // api base_url
  timeout: 15000, // 请求超时时间
});
const homeSortAPIList = [

];
const sortAPIList = [

];

const analyticsTrackAPIList = [];

const err = (error) => {
  // console.info(`\n\n-------- error Info Begin --------\n\n`, error, `\n\n-------- error Info end   --------\n\n`)
  if (error.response) {
    let data = error.response.data;
    const token = Vue.ls.get(ACCESS_TOKEN);
    console.log("------异常响应------", token);
    console.log("------异常响应------", error.response.status);
    switch (error.response.status) {
      case 403:
        // notification.error({ message: "系统提示", description: "拒绝访问", duration: 4 });
        break;
      case 500:
        {
          console.log("------error.response------", error.response);
          const type = error.response.request.responseType;
          if (type === "blob") {
            blobToJson(data);
            break;
          }
          // notification.error({ message: '系统提示', description: 'Token失效，请重新登录!', duration: 4 })
          if (token && data.message.includes("Token失效")) {
            Vue.ls.remove(ACCESS_TOKEN);
            // window.location.reload();
            if (path != "/" && path.indexOf('/user/login') == -1) {
              window.location.reload()
            }
            //       }
            // update-begin- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
            // Modal.error({
            //   title: '登录已过期',
            //   content: '很抱歉，登录已过期，请重新登录',
            //   okText: '重新登录',
            //   mask: false,
            //   onOk: () => {
            //     store.dispatch('Logout').then(() => {
            //       Vue.ls.remove(ACCESS_TOKEN)
            //       try {
            //         let path = window.document.location.pathname
            //         console.log("location pathname -> "+path)
            //         if(path!="/" && path.indexOf('/user/login')==-1){
            //           window.location.reload()
            //         }
            //       }catch (e) {
            //         window.location.reload()
            //       }
            //     })
            //   }
            // })
          }
        }

        break;

      case 404:
        // notification.error({ message: "系统提示", description: "很抱歉，资源未找到!", duration: 4 });
        break;
      case 504:
        // notification.error({ message: "系统提示", description: "网络超时" });
        break;
      case 401:
        // notification.error({ message: "系统提示", description: "未授权，请重新登录", duration: 4 });
        Vue.ls.remove(ACCESS_TOKEN);
        if (token) {
          store.dispatch("user/logoutAction").then(() => {
            setTimeout(() => {
              window.location.reload();
            }, 1500);
          });
        }
        break;
      default:
        // notification.error({
        //   message: "系统提示",
        //   description: data.message,
        //   duration: 4,
        // });
        break;
    }
  }
  return Promise.reject(error);
};

// request interceptor
service.interceptors.request.use(
  (config) => {
    const url = config.url;
    if (config.method.toUpperCase() === "GET") {
      const parameters = config.data;

      if (parameters && parameters.constructor === Object && Object.keys(parameters).length > 0) {
        var getParameters = "";
        var isFristElement = true;

        for (const key in parameters) {
          if (isFristElement) {
            isFristElement = false;
            getParameters += key + "=" + parameters[key];
          } else {
            getParameters += "&" + key + "=" + parameters[key];
          }
        }
        config.url = config.url + "?" + getParameters;
      }
    }

    var channel = "0";

    const timestamp = signMd5Utils.getDateTimeToString();
    var sharedParams = {
      _t: timestamp,
      column: "createTime",
      order: "desc",
      isLocked: "0",
      auditStatus: "2",
    };

    // 这里顺序一定要在column: 'createTime'设置之后
    if (sortAPIList.indexOf(config.url) > -1) {
      sharedParams = {
        ...sharedParams,
        column: "sort",
        order: "asc",
      };
    }

    // 这里顺序一定要在column: 'createTime'设置之后
    if (homeSortAPIList.indexOf(config.url) > -1) {
      sharedParams = {
        ...sharedParams,
        column: "homeSort",
        order: "asc",
      };
    }
    // indexOf()方法返回在数组中可以找到一个给定元素的第一个索引，如果不存在，则返回-1。

    if (analyticsTrackAPIList.indexOf(config.url) > -1) {
      sharedParams = {
        ...sharedParams,
        channel,
      };
    }

    //在URL部分定义全局筛选条件
    config.params = {
      ...sharedParams,
      ...config.params,
    };

    if (config.method == "post" && Object.prototype.toString.call(config.data) != "[object FormData]") {
      config.data = {
        ...sharedParams,
        ...config.data,
      };
    }

    const signParameters = {
      ...config.params,
      ...config.data,
    };

    //去掉 Url 里的时间戳 与后端算法保存一致
    delete signParameters._t;

    let sign = signMd5Utils.getSign(url, signParameters);
    const token = Vue.ls.get(ACCESS_TOKEN);
    let tenantid = "0";
    let signHeader = {
      "X-Sign": sign,
      "X-TIMESTAMP": timestamp,
      "X-Access-Token": token,
      "tenant-id": tenantid,
    };
    config.headers = signHeader;

    config.url = encodeURI(config.url);

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use((response) => {
  return response.data;
}, err);

const installer = {
  vm: {},
  install(Vue, router = {}) {
    Vue.use(VueAxios, router, service);
  },
};
/**
 * Blob解析
 * @param data
 */
function blobToJson(data) {
  let fileReader = new FileReader();
  let token = Vue.ls.get(ACCESS_TOKEN);
  fileReader.onload = function () {
    try {
      let jsonData = JSON.parse(this.result); // 说明是普通对象数据，后台转换失败
      console.log("jsonData", jsonData);
      if (jsonData.status === 500) {
        console.log("token----------》", token);
        if (token && jsonData.message.includes("Token失效")) {
          // Modal.error({
          //   title: "登录已过期",
          //   content: "很抱歉，登录已过期，请重新登录",
          //   okText: "重新登录",
          //   mask: false,
          //   onOk: () => {
          //     store.dispatch("Logout").then(() => {
          //       Vue.ls.remove(ACCESS_TOKEN);
          //       window.location.reload();
          //     });
          //   },
          // });
        }
      }
    } catch (err) {
      // 解析成对象失败，说明是正常的文件流
      console.log("blob解析fileReader返回err", err);
    }
  };
  fileReader.readAsText(data);
}

export { installer as VueAxios, service as axios };
